<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template>
  <div class="app-container calendar-list-container">
    <basic-container>

      <el-container>
        <el-aside width="200px">
          <avue-tree :option="treeOptionRole"
                     ref="form"
                     :data="treeDataRole"
                     :permission="getPermission"
                     @save="handleInsert"
                     @update="handleUpdate"
                     @del="handleDel"
                     @node-click="nodeClick">
            <template #menu="scope">
              <el-button  link type="primary"  style="margin-top: 5px;margin-bottom: 5px" icon="el-icon-setting" @click="handlePermission(scope.node.data)">权限</el-button>
            </template>
          </avue-tree>
        </el-aside>
        <el-main>
          <basic-container>
          <avue-crud
                  ref="itemCrud"
                  v-model:page="itemPage"
                  :data="tableItemData"
                  @search-change="jtemSearchChange"
                  v-model:search="searchForm2"
                  :option="tableItemOption"
                  @size-change="itemSizeChange"
                  @current-change="itemCurrentChange"

          >
          <template #menu-left="{size}">
            <el-button type="primary"  @click="addUser()">新增用户</el-button>
          </template>
          </avue-crud>
        </basic-container>

        </el-main>
      </el-container>


    </basic-container>

    <el-dialog v-model="dialogPermissionVisible" :close-on-click-modal="false" title="分配权限">
      <div class="dialog-main-tree">
        <el-input
                placeholder="输入关键字进行过滤"
                v-model="filterText" @change="handFilterText">
        </el-input>
        <el-tree
          ref="menuTree"
          :data="treeData"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
          :props="defaultProps"
          :filter-node-method="filterNode"
          class="filter-tree"
          node-key="id"
          highlight-current
          show-checkbox
          :default-expanded-keys="twoKeys"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="updatePermession(roleId)">更 新</el-button>
        <el-button type="default" size="small" @click="cancal()">取消</el-button>
      </div>
    </el-dialog>


    <user-choose :column="userColumn" :value="userValue"  @userSelected="userSelected" ref="myUserChoose" ></user-choose>

  </div>
</template>

<script>
 import curdMixin from '@/framework-core/mixins/crud';
import {tableOption} from "../user/user";
  import {listByTenant} from "@/framework-admin/api/admin/role";

import {fetchMenuTree,fetchMenuTreeByMng, fetchMenuByRoleId,permissionUpdateRoleMenu} from "@/framework-admin/api/admin/menu";
 import {pageCore, listCore, getCore, saveCore,delCore,importCore,exportCore} from "@/framework-core/api/core/api";
 import website  from '@/framework-core/config/website';
 import userChoose from '@/framework-core/components/user/user/userChoose.vue'
 import iconList from "@/framework-core/config/iconList";

 import {setOrgRole3} from '@/framework-admin/api/admin/user';

export default {
  name: "TableRole",
  mixins: [curdMixin],
  components: {userChoose},
  data() {
    return {
      pageConfig:{"url":"sys/role"},

      userColumn:{userType:'org',multiple:false,hideUserSelected:true},
      userValue:"",
      treeDataRole:[],
      filterText:"",
      treeOptionRole: {
        defaultExpandAll: false,
        formOption: {
          labelWidth: 120,
          column: [
            {
              label: '角色名称',
              prop: 'name',
              span: 24,
              rules: [{
                required: true,
                message: '角色名称不能为空',
                trigger: 'blur'
              }],
              'search': true,
            },
            {
              label: '角色标识',
              prop: 'code',
              span: 24,
              editDisabled: true,
              rules: [{
                required: true,
                message: '角色标识不能为空',
                trigger: 'blur'
              }],
              'search': true,
            },
            {
              label: '图标',
              prop: 'icon',
              type: 'icon',
              value: 'el-icon-user',
              iconList: [{
                label: '符号图标',
                list: iconList[0].list
              }]
            },
            {
              label: '角色等级',
              prop: 'level',
              span: 24,
              editDisabled: true
            },
            {
              type: 'textarea',
              label: '角色描述',
              prop: 'description',
              overHidden: true,
              span: 24,
              row: true,
              minRows: 2,
              rules: [{
                max: 128,
                message: '长度在 128 个字符内',
                trigger: 'blur'
              }]
            }
            ]
        },
        props: {
          labelText: '标题',
          label: 'name',
          value: 'id',
          children: 'children'
        }
      },
      selectRoleId:"",
      form: {},
      itemPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: website.pageSize // 每页显示多少条
      },
      searchForm2: {},
      tableLoading: true,
      tableItemData: [],
      tableItemOption: tableOption,
      twoKeys:[],
      //dsScope数据权限相关
      dsScopeData: [],
      checkedDsScope: [],
      defaultProps: {
        label: "name",
        value: "id"
      },

      //权限相关
      dialogPermissionVisible: false,
      treeData: [],
      checkedKeys: [],

      menuIds: "",
      roleId: undefined,
      roleCode: undefined,
      rolesOptions: undefined
    };
  },

  computed: {
    ...mapState({
      permissions: (state) => state.user.permission,
    }),
  },

  created() {
    this.init();
  },

  methods: {
    init() {
      this.tableItemOption.menu =false;
      this.tableItemOption.editBtn= false;
      this.tableItemOption.delBtn= false;
      this.tableItemOption.addBtn= false;

      // this.tableItemOption.addBtnText= "选择用户";
      // this.tableItemOption.delBtnText= "删除用户";
     this.getRoles();
     this.getItemPage();

      this.$initOptionDict(this.tableItemOption.column);

    },

    addUser(){
        if(!this.selectRoleId){
          this.$message.error("选择角色");
           return;
        }
        this.$refs.myUserChoose.toShow()

    },
    userSelected(data) {
     // alert("待处理，新增用户：" + JSON.stringify(data))
      if (!data || data.length == 0) {
        return
      }
      setOrgRole3({roleId: this.selectRoleId, userId: data[0].id}).then(() => {
        this.getItemPage();
        this.$message.success("添加成功");
      }).catch(() => {
      });
    },

    handleInsert: function(node, row, done) {

      saveCore(this.pageConfig.url, row).then(() => {
        this.getRoles();
        this.$message.success("创建成功");
        if (done) {
          done();
        }
      }).catch(() => {
        if (done) {
          done();
        }
      });
    },
    handleUpdate: function(node, row, done) {
      saveCore(this.pageConfig.url, row).then(() => {
        this.getRoles();
        this.$message.success("创建成功");
        if (done) {
          done();
        }
      }).catch(() => {
        if (done) {
          done();
        }
      });
    },
    handleDel: function(row, index) {

      var $that = this;
      this.$confirm("是否确认删除：" +row.name, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
              .then(function() {
                return delCore($that.pageConfig.url,row);
              })
              .then(() => {
                $that.getRoles();
                $that.$message.success("删除成功");
              });

    },

    nodeClick(row){
      this.selectRoleId  = row.id;
      this.getItemPage();
    },

    getRoles(){
      this.tableLoading = true;
      listByTenant({}).then(response => {
        this.treeDataRole = response.data.data.data;
        this.tableLoading = false;
      }).catch(() => {
        this.tableLoading = false;
      });
    },

    getPermission:function(key, row, index) {
      if(index>=0 &&"rt" === key){
        return !(vaildData(row.canDo && this.permissions["sys_rolemenu_set_post"]));
      }
      return this.getCommPermission(key, row, index) && row.isSys!=1;
    },
    getItemPage(done) {
       this.tableLoading = true;
      pageCore(
              "sys/user",
              this.buildParam2()
      )
              .then(response => {
                this.tableItemData = response.data.data.records;
                this.itemPage.total = response.data.data.total;
                this.tableLoading = false;
                if(done){
                  done();
                }
              })
              .catch(() => {
                this.tableLoading = false;
                if(done){
                  done();
                }
              });
    },
    jtemSearchChange(params,done){
        this.getItemPage(done);
    },
    itemSizeChange(pageSize) {
      this.itemPage.pageSize = pageSize;
      this. getItemPage();
    },
    itemCurrentChange(current) {
      this.itemPage.currentPage = current;
      this. getItemPage();
    },

    buildParam2() {
      var entity = Object.assign(
              {},
              {},
              this.searchForm2
      );
      entity.roleId = this.selectRoleId;
      var obj = {
        pageNum: this.itemPage.currentPage,
        pageSize: this.itemPage.pageSize,
        // sorts: sorts
      };
      obj.entity = entity;
      if (this.beforParam) {
        this.beforParam(obj.entity);
      }
      return obj;
    },

    //分配权限相关操作
    cancal() {
      this.dialogPermissionVisible = false;
    },
    handlePermission(row) {
      debugger
      let $that = this;
      fetchMenuByRoleId(row.id)
        .then(response => {
          this.checkedKeys = response.data.data.data;
          return fetchMenuTreeByMng();
        })
        .then(response => {
          // 解析出所有的太监节点
          $that.treeData = [];
          const menu = {id: 0, name: "根菜单", children: []};
          $that.twoKeys.push(0);
          menu.children = response.data.data.data;
          $that.treeData.push(menu);



          $that.checkedKeys = $that.resolveAllEunuchNodeId($that.treeData, $that.checkedKeys, []);
          $that.dialogPermissionVisible = true;
          $that.roleId = row.id;
          $that.roleCode = row.code;
        });
    },
    /**
     * 解析出所有的太监节点id
     * @param json 待解析的json串
     * @param idArr 原始节点数组
     * @param temp 临时存放节点id的数组
     * @return 太监节点id数组
     */
    resolveAllEunuchNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i];
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          this.resolveAllEunuchNodeId(item.children, idArr, temp);
        } else {
          temp.push(idArr.filter(id => id === item.id));
        }
      }
      return temp;
    },
    handFilterText() {
      this.$refs.menuTree.filter(this.filterText);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1 || (data.path	 && ((data.path.indexOf(value) !== -1) || (data.path.replace("_","/").indexOf(value) !== -1) ) );
    },

    updatePermession(roleId) {
      this.menuIds = this.$refs.menuTree
        .getCheckedKeys()
         .join(";")
        // .concat(";")
        // .concat(this.$refs.menuTree.getHalfCheckedKeys().join(";"));

      permissionUpdateRoleMenu(roleId, this.menuIds).then(() => {
        this.dialogPermissionVisible = false;
        this.$message.success("修改成功");
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  :deep(.avue-tree){
    margin-right: 10px;
  }
</style>
